<template>
  <div class="search-page">
    <!-- 引入顶部导航栏 -->
    <TopNav />

    <!-- 标题与搜索框 -->
    <div class="search-header">
      <h2>商品搜索</h2>
      <p>输入关键词，查找您想要的商品</p>
    </div>

    <!-- 搜索表单 -->
    <div class="search-form">
      <input
        type="text"
        v-model="searchQuery"
        placeholder="请输入商品名称..."
        @keyup.enter="performSearch"
      />
      <button @click="performSearch">搜索</button>
    </div>

    <!-- 搜索结果 -->
    <div v-if="searchQuery" class="search-results-container">
      <div class="search-results">
        <h3>搜索结果：</h3>
        <div v-if="loading" class="loading">加载中...</div>
        <div v-else-if="goods.length" class="goods-list">
          <div v-for="good in goods" :key="good.id" class="good-card-wrapper" @click="goToDetail(good)">
            <div class="good-card">
              <img :src="good.gImage" alt="商品图片" @error="handleImageError" />
              <div class="good-info">
                <h3>{{ good.gName }}</h3>
                <p>价格：￥{{ good.gPrice }}</p>
                <p>描述：{{ good.gDesciption }}</p>
              </div>
            </div>
            <button class="buy-now-button" @click.stop="buyNow(good)">立即购买</button>
          </div>
        </div>
        <div v-else class="no-result">没有找到相关商品</div>
      </div>
    </div>

    <!-- 热门搜索关键词 -->
    <div v-if="!searchQuery || goods.length === 0" class="hot-searches">
      <h4>热门搜索：</h4>
      <span
        v-for="keyword in hotKeywords"
        :key="keyword"
        class="keyword-tag"
        @click="searchKeyword(keyword)"
      >{{ keyword }}</span>
    </div>

    <!-- 最近搜索记录 -->
    <div v-if="recentSearches.length && (!searchQuery || goods.length === 0)" class="recent-searches">
      <h4>最近搜索：
        <span @click="clearRecentSearches" class="clear-button">清空全部</span>
      </h4>
      <ul>
        <li v-for="(keyword, index) in recentSearches" :key="index" @click="searchKeyword(keyword)">
          <span>{{ keyword }}</span>
          <span class="delete-icon" @click.stop="removeRecentSearch(keyword)">×</span>
        </li>
      </ul>
    </div>

    <!-- 默认提示 -->
    <div v-else-if="!searchQuery && goods.length === 0" class="no-query">
      <p>请输入关键词进行搜索</p>
    </div>

    <!-- 推荐商品 -->
    <div v-if="!searchQuery || goods.length === 0" class="recommendations">
      <h4>猜你喜欢</h4>
      <div class="recommendation-cards">
        <div
          class="card"
          v-for="item in recommendedItems"
          :key="item"
          @click="searchKeyword(item)"
        >
          <img :src="getImageUrl(item)" :alt="item" @error="handleImageError" />
          <p>{{ item }}</p>
        </div>
      </div>
    </div>

    <!-- 分类组件 -->
    <div class="category-list-container">
      <CategoryList @category-selected="handleCategorySelected" />
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import goodApi from '@/api/controller'
import pingguo from '@/assets/images/pingguo.jpg'
import niunai from '@/assets/images/niunai.jpg'
import jidan from '@/assets/images/jidan.jpg'
import xifashui from '@/assets/images/xifashui.jpg'
import zhijin from '@/assets/images/zhijin.jpg'
import placeholder from '@/assets/images/placeholder.jpg'
import CategoryList from '@/components/CategoryList.vue'
import TopNav from '@/components/TopNav.vue' // 导入 TopNav 组件
import searchApi from '@/api/search'
import { useRouter } from 'vue-router'

// 数据
const searchQuery = ref('')
const goods = ref([])
const loading = ref(false)
const hotKeywords = ['草莓', '牛奶', '香蕉', '牛肉', '纸巾']
const recentSearches = ref(JSON.parse(localStorage.getItem('recentSearches') || '[]'))
const recommendedItems = ['苹果', '牛奶', '鸡蛋', '洗发水', '纸巾']

// 图片映射表
const imageMap = {
  '苹果': pingguo,
  '牛奶': niunai,
  '鸡蛋': jidan,
  '洗发水': xifashui,
  '纸巾': zhijin,
  'placeholder': placeholder
}

function getImageUrl(keyword) {
  return imageMap[keyword] || imageMap['placeholder']
}

function handleImageError(event) {
  event.target.src = imageMap['placeholder']
}

// 根据分类搜索商品
async function searchByCategory(categoryName) {
  console.log('点击分类:', categoryName)

  searchQuery.value = categoryName
  loading.value = true
  goods.value = []

  try {
    // 调用接口，传参为 categoryName
    const response = await goodApi.getGoodByCategory(categoryName)
    console.log('接口返回:', response)

    if (response.code === 200 && Array.isArray(response.data)) {
      goods.value = response.data
    } else {
      goods.value = []
    }
  } catch (error) {
    console.error('分类搜索失败:', error)
    goods.value = []
  } finally {
    loading.value = false
  }

  // 添加分类到最近搜索
  if (!recentSearches.value.includes(categoryName)) {
    recentSearches.value.unshift(categoryName)
    if (recentSearches.value.length > 10) {
      recentSearches.value.pop()
    }
    localStorage.setItem('recentSearches', JSON.stringify(recentSearches.value))
  }
}

// 普通搜索（关键词）
async function performSearch() {
  const keyword = searchQuery.value.trim()
  if (!keyword) {
    goods.value = []
    return
  }

  loading.value = true
  goods.value = []

  try {
    const response = await goodApi.getGoodListPage(1, 10, keyword)
    if (response.code === 200) {
      goods.value = response.rows || []
    } else {
      goods.value = []
    }
  } catch (error) {
    console.error('搜索失败:', error)
    goods.value = []
  } finally {
    loading.value = false
  }

  // 添加到最近搜索
  if (!recentSearches.value.includes(keyword)) {
    recentSearches.value.unshift(keyword)
    if (recentSearches.value.length > 10) {
      recentSearches.value.pop()
    }
    localStorage.setItem('recentSearches', JSON.stringify(recentSearches.value))
  }
}

function searchKeyword(keyword) {
  searchQuery.value = keyword
  performSearch()
}

function removeRecentSearch(keyword) {
  recentSearches.value = recentSearches.value.filter(k => k !== keyword)
  localStorage.setItem('recentSearches', JSON.stringify(recentSearches.value))
}

function clearRecentSearches() {
  recentSearches.value = []
  localStorage.removeItem('recentSearches')
}

const router = useRouter()

function buyNow(good) {
  goToDetail(good)
}

function goToDetail(good) {
  const { id } = good
  searchApi.getGoodMatchById(id).then(response => {
    if (response.code === 200) {
      router.push({ name: 'GoodsDetail', params: { id } })
    } else {
      alert('请求失败')
    }
  }).catch(error => {
    console.error('调用接口失败:', error)
    alert('网络异常')
  })
}

// 点击分类时调用的方法
function handleCategorySelected(categoryName) {
  searchByCategory(categoryName)
}
</script>

<style scoped>
.search-page {
  max-width: 960px;
  margin: 60px auto;
  padding: 20px;
  font-family: Arial, sans-serif;
  position: relative;
}

.search-header {
  text-align: center;
  margin-bottom: 20px;
  width: 100%;
}

.search-form {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.search-form input[type="text"] {
  flex: 1;
  padding: 10px;
  border-radius: 4px;
  border: 1px solid #ccc;
  font-size: 16px;
}

.search-form button {
  padding: 10px 20px;
  background-color: #2e7d32;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.search-form button:hover {
  background-color: #388e3c;
}

.search-results-container {
  width: 100%;
}

.category-list-container {
  position: fixed;
  top: 60px;
  right: 20px;
  width: 350px;
  z-index: 10;
}

.category-list {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 24px;
  width: 100%;
}

.goods-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}

.good-card-wrapper {
  text-align: center;
  margin-bottom: 20px;
  cursor: pointer;
}

.good-card {
  border: 1px solid #eee;
  border-radius: 6px;
  padding: 15px;
  background-color: #fff;
  transition: box-shadow 0.3s;
}

.good-card:hover {
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.good-card img {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 4px;
  margin-bottom: 10px;
}

.good-info h3 {
  font-size: 16px;
  margin: 5px 0;
}

.good-info p {
  margin: 4px 0;
  color: #666;
}

.buy-now-button {
  background-color: red;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 8px 16px;
  cursor: pointer;
  margin-top: 10px;
  font-size: 16px;
}

.buy-now-button:hover {
  background-color: darkred;
}

.hot-searches {
  margin-bottom: 20px;
  width: 100%;
}

.keyword-tag {
  display: inline-block;
  margin-right: 10px;
  margin-bottom: 10px;
  padding: 5px 10px;
  background-color: #e8f5e9;
  color: #2e7d32;
  border-radius: 4px;
  cursor: pointer;
}

.keyword-tag:hover {
  background-color: #c8e6c9;
}

.recent-searches {
  margin-bottom: 20px;
  width: 100%;
}

.recent-searches ul {
  list-style: none;
  padding-left: 0;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.recent-searches li {
  position: relative;
  background-color: #f0f0f0;
  padding: 6px 30px 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.recent-searches li:hover {
  background-color: #ddd;
}

.delete-icon {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 14px;
  color: #999;
  cursor: pointer;
}

.delete-icon:hover {
  color: red;
}

.clear-button {
  margin-left: 10px;
  font-size: 12px;
  font-weight: 500;
  color: #757775;
  background-color: #eeeeee;
  padding: 2px 8px;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.clear-button:hover {
  background-color: #e0e0e0;
  color: #d32f2f;
  transform: scale(1.05);
}

.no-query {
  text-align: center;
  color: #999;
  width: 100%;
}

.recommendations {
  margin-top: 40px;
  width: 100%;
}

.recommendation-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 20px;
  width: 100%;
}

.card {
  background-color: #fff;
  border: 1px solid #eee;
  border-radius: 6px;
  padding: 15px;
  text-align: center;
  cursor: pointer;
  transition: box-shadow 0.3s;
}

.card:hover {
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.card img {
  width: 100%;
  height: 120px;
  object-fit: cover;
  border-radius: 4px;
  margin-bottom: 10px;
}

.loading,
.no-result {
  text-align: center;
  padding: 40px;
  font-size: 16px;
  color: #999;
  width: 100%;
}
</style>